<template>
  <a-drawer
    :width="500"
    :visible="show"
    :footer="false"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title> {{ data.type }}组件编辑 </template>
    <div class="setting-content">
      <!-- 组件自身属性 -->
      <div class="setting-header flex items-center">
        <span class="header-title">组件宽度</span>
        <a-select v-model="data.width" placeholder="请选择" allow-clear>
          <a-option value="default">默认</a-option>
          <a-option value="small">小</a-option>
          <a-option value="middle">中</a-option>
          <a-option value="max">大</a-option>
        </a-select>
      </div>
      <div class="setting-header flex items-center">
        <span class="header-title">组件背景</span>
        <a-select v-model="data.bgColor" placeholder="请选择" allow-clear>
          <a-option value="#ffffff">白色</a-option>
          <a-option value="#F7F7FA">灰色</a-option>
        </a-select>
      </div>

      <a-button-group type="primary">
        <a-button size="mini" @click="handleAdd('Article')"
          ><template #icon><icon-plus /></template> Article
        </a-button>
        <a-button size="mini" @click="handleAdd('Contact')"
          ><template #icon><icon-plus /></template> Contact
        </a-button>
        <a-button size="mini" @click="handleAdd('Image')"
          ><template #icon><icon-plus /></template> Image
        </a-button>
        <a-button size="mini" @click="handleAdd('ImageList')"
          ><template #icon><icon-plus /></template> ImageList
        </a-button>
        <a-button size="mini" @click="handleAdd('Video')"
          ><template #icon><icon-plus /></template> Video
        </a-button>
      </a-button-group>

      <!-- 子组件属性 -->
      <div class="setting-body">
        <draggable
          v-model="data.data"
          :component-data="{
            tag: 'div',
            type: 'transition-group',
            name: !drag ? 'flip-list' : null,
          }"
          v-bind="dragOptions"
          @start="drag = true"
          @end="drag = false"
          item-key="id"
        >
          <template #item="{ element: item }">
            <div class="setting-item">
              <p class="item-name">{{ item.type }}</p>
              <div class="btn-group">
                <div class="drag-handle">
                  <icon-drag-arrow class="drag-icon" />
                </div>
                <icon-delete
                  class="btn-delete"
                  @click="handleDelete(item.id)"
                />
              </div>

              <template v-if="item.type === 'Article'">
                <p class="item-title">标题</p>
                <a-input
                  v-model="item.title"
                  placeholder="请输入标题"
                  allow-clear
                />

                <p class="item-title">内容</p>
                <RichTextEditor v-model="item.content" :name="`ArticleList_editor_${item.id}`"></RichTextEditor>

                <p class="item-title">按钮</p>
                <draggable
                  v-model="item.buttonList"
                  :component-data="{
                    tag: 'div',
                    type: 'transition-group',
                    name: !drag ? 'flip-list' : null,
                  }"
                  v-bind="buttonDragOptions"
                  :disabled="!shouldShowDragHandle(item.buttonList)"
                  @start="drag = true"
                  @end="drag = false"
                  item-key="id"
                >
                  <template #item="{ element: button }">
                    <div
                      class="item-button draggable-item"
                      :class="{
                        'sortable-disabled': !shouldShowDragHandle(
                          item.buttonList
                        ),
                      }"
                      :key="button.id"
                    >
                      <div class="btn-group">
                        <div
                          v-if="shouldShowDragHandle(item.buttonList)"
                          class="drag-handle"
                        >
                          <icon-drag-arrow class="drag-icon" />
                        </div>
                        <icon-delete
                          class="btn-delete"
                          @click="
                            handleDeleteButton(item.buttonList, button.id)
                          "
                        />
                      </div>
                      <a-button type="primary">{{ button.text }}</a-button>
                      <div class="item-action flex items-center">
                        <a-input
                          class="action-text"
                          v-model="button.text"
                          placeholder="按钮文本"
                          allow-clear
                        />
                        <a-input
                          v-model="button.url"
                          placeholder="按钮链接"
                          allow-clear
                        />
                      </div>
                      <a-checkbox v-model="button.isExternal"
                        >是否外部链接</a-checkbox
                      >
                    </div>
                  </template>
                </draggable>
                <div
                  class="item-add-btn flex items-center"
                  @click="handleAddButton(item.buttonList)"
                >
                  <icon-plus />
                  <span class="btn-text">添加按钮</span>
                </div>

                <p class="item-title">链接</p>
                <draggable
                  v-model="item.linkList"
                  :component-data="{
                    tag: 'div',
                    type: 'transition-group',
                    name: !drag ? 'flip-list' : null,
                  }"
                  v-bind="linkDragOptions"
                  :disabled="!shouldShowDragHandle(item.linkList)"
                  @start="drag = true"
                  @end="drag = false"
                  item-key="id"
                >
                  <template #item="{ element: link }">
                    <div
                      class="item-button draggable-item"
                      :class="{
                        'sortable-disabled': !shouldShowDragHandle(
                          item.linkList
                        ),
                      }"
                      :key="link.id"
                    >
                      <div class="btn-group">
                        <div
                          v-if="shouldShowDragHandle(item.linkList)"
                          class="drag-handle"
                        >
                          <icon-drag-arrow class="drag-icon" />
                        </div>
                        <icon-delete
                          class="btn-delete"
                          @click="handleDeleteLink(item.linkList, link.id)"
                        />
                      </div>

                      <a-link href="link">{{ link.text }}</a-link>
                      <div class="item-action flex items-center">
                        <a-input
                          class="action-text"
                          v-model="link.text"
                          placeholder="按钮文本"
                          allow-clear
                        />
                        <a-input
                          v-model="link.url"
                          placeholder="按钮链接"
                          allow-clear
                        />
                      </div>
                      <a-checkbox v-model="link.isExternal"
                        >是否外部链接</a-checkbox
                      >
                    </div>
                  </template>
                </draggable>
                <div
                  class="item-add-btn flex items-center"
                  @click="handleAddLink(item.linkList)"
                >
                  <icon-plus />
                  <span class="btn-text">添加链接</span>
                </div>
              </template>

              <template v-if="item.type === 'Contact'">
                <p class="item-title">标题</p>
                <a-input
                  v-model="item.title"
                  placeholder="请输入标题"
                  allow-clear
                />

                <p class="item-title">内容</p>
                <RichTextEditor v-model="item.content" :name="`ArticleList_editor_${item.id}`"></RichTextEditor>

                <p class="item-title">分类</p>
                <draggable
                  v-model="item.categories"
                  :component-data="{
                    tag: 'div',
                    type: 'transition-group',
                    name: !drag ? 'flip-list' : null,
                  }"
                  v-bind="categoryDragOptions"
                  :disabled="!shouldShowDragHandle(item.categories)"
                  @start="drag = true"
                  @end="drag = false"
                  item-key="id"
                >
                  <template #item="{ element: category }">
                    <div
                      class="item-button draggable-item"
                      :class="{
                        'sortable-disabled': !shouldShowDragHandle(
                          item.categories
                        ),
                      }"
                      :key="category.id"
                    >
                      <div class="btn-group">
                        <div
                          v-if="shouldShowDragHandle(item.categories)"
                          class="drag-handle"
                        >
                          <icon-drag-arrow class="drag-icon" />
                        </div>
                        <icon-delete
                          class="btn-delete"
                          @click="
                            handleDeleteCategory(item.categories, category.id)
                          "
                        />
                      </div>
                      <icon-delete
                        class="btn-delete"
                        @click="
                          handleDeleteCategory(item.categories, category.id)
                        "
                      />
                      <a-link href="link">{{ category.text }}</a-link>
                      <div class="item-action flex items-center">
                        <a-input
                          v-model="category.text"
                          placeholder="分类名称"
                          allow-clear
                        />
                      </div>
                    </div>
                  </template>
                </draggable>
                <div
                  class="item-add-btn flex items-center"
                  @click="handleAddCategory(item.categories)"
                >
                  <icon-plus />
                  <span class="btn-text">添加分类</span>
                </div>

                <p class="item-title">链接</p>
                <draggable
                  v-model="item.linkList"
                  :component-data="{
                    tag: 'div',
                    type: 'transition-group',
                    name: !drag ? 'flip-list' : null,
                  }"
                  v-bind="linkDragOptions"
                  :disabled="!shouldShowDragHandle(item.linkList)"
                  @start="drag = true"
                  @end="drag = false"
                  item-key="id"
                >
                  <template #item="{ element: link }">
                    <div
                      class="item-button draggable-item"
                      :class="{
                        'sortable-disabled': !shouldShowDragHandle(
                          item.linkList
                        ),
                      }"
                      :key="link.id"
                    >
                      <div class="btn-group">
                        <div
                          v-if="shouldShowDragHandle(item.linkList)"
                          class="drag-handle"
                        >
                          <icon-drag-arrow class="drag-icon" />
                        </div>
                        <icon-delete
                          class="btn-delete"
                          @click="handleDeleteLink(item.linkList, link.id)"
                        />
                      </div>
                      <a-link href="link">{{ link.text }}</a-link>
                      <div class="item-action flex items-center">
                        <a-input
                          class="action-text"
                          v-model="link.text"
                          placeholder="按钮文本"
                          allow-clear
                        />
                        <a-input
                          v-model="link.url"
                          placeholder="按钮链接"
                          allow-clear
                        />
                      </div>
                      <a-checkbox v-model="link.isExternal"
                        >是否外部链接</a-checkbox
                      >
                    </div>
                  </template>
                </draggable>
                <div
                  class="item-add-btn flex items-center"
                  @click="handleAddLink(item.linkList)"
                >
                  <icon-plus />
                  <span class="btn-text">添加链接</span>
                </div>
              </template>

              <template v-if="item.type === 'Image'">
                <img class="item-img" :src="item.imgSrc" />
                <div class="item-uplaod flex items-center">
                  <a-input
                    v-model="item.imgSrc"
                    placeholder="请输入标题"
                    allow-clear
                  />
                  <Upload v-model="item.imgSrc" :name="`ArticleList_${item.id}`" button-class="fit-content" />
                </div>
                <a-input
                  class="mt-2"
                  v-model="item.caption"
                  placeholder="图片描述"
                  allow-clear
                />
                <a-input
                  class="mt-2"
                  v-model="item.alt"
                  placeholder="图片alt"
                  allow-clear
                />
                <a-checkbox class="pt-2" v-model="item.isRound"
                  >圆角</a-checkbox
                >
              </template>

              <template v-if="item.type === 'ImageList'">
                <p class="item-title">图片组</p>
                <div class="item-img-list">
                  <draggable
                    v-model="item.imageList"
                    :component-data="{
                      tag: 'div',
                      type: 'transition-group',
                      name: !drag ? 'flip-list' : null,
                    }"
                    v-bind="imageDragOptions"
                    :disabled="!shouldShowDragHandle(item.imageList)"
                    @start="drag = true"
                    @end="drag = false"
                    item-key="id"
                  >
                    <template #item="{ element: img }">
                      <div
                        class="img-list-item flex draggable-item"
                        :class="{
                          'sortable-disabled': !shouldShowDragHandle(
                            item.imageList
                          ),
                        }"
                        :key="img.id"
                      >
                        <div class="btn-group">
                          <div
                            v-if="shouldShowDragHandle(item.imageList)"
                            class="drag-handle"
                          >
                            <icon-drag-arrow class="drag-icon" />
                          </div>
                          <icon-delete
                            class="btn-delete"
                            @click="handleDeleteImage(item.imageList, img.id)"
                          />
                        </div>

                        <div class="item-img-box" v-if="img.src">
                          <!-- <icon-close-circle-fill class="item-img-dlete" @click="handleDeleteImage(item.imageList, img.id)" /> -->
                          <img class="item-img small-img" :src="img.src" />
                        </div>

                        <div class="item-right flex-1">
                          <a-input
                            style="margin-bottom: 12px"
                            v-model="img.src"
                            placeholder="请输入图片路径"
                            allow-clear
                          />
                          <Upload v-model="img.src" :name="`ArticleList_${img.id}`" button-class="fit-content" />
                        </div>
                      </div>
                    </template>
                  </draggable>
                </div>
                <div
                  class="item-add-btn flex items-center"
                  @click="handleAddImage(item.imageList)"
                >
                  <icon-plus />
                  <span class="btn-text">添加图片</span>
                </div>
              </template>

              <template v-if="item.type === 'Video'">
                <p class="item-title">视频</p>
                <video class="item-img" :src="item.videoSrc" controls></video>
                <div class="item-uplaod flex items-center">
                  <a-input
                    v-model="item.videoSrc"
                    placeholder="请输入视频链接"
                    allow-clear
                  />
                  <Upload v-model="item.videoSrc" :name="`ArticleList_${item.id}`" button-class="fit-content" />
                </div>
                <img class="item-img" :src="item.imgSrc" />
                <div class="item-uplaod flex items-center">
                  <a-input
                    v-model="item.imgSrc"
                    placeholder="视频封面"
                    allow-clear
                  />
                  <Upload v-model="item.imgSrc" :name="`ArticleList_${item.id}`" button-class="fit-content" />
                </div>
              </template>
            </div>
          </template>
        </draggable>
      </div>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import Upload from '@/common/Upload/index.vue'
import { ref, computed, defineAsyncComponent } from "vue";
import { randomString } from "@/utils/common";

// 动态导入 draggable，避免 SSR 问题
const draggable = defineAsyncComponent(() => import("vuedraggable"));
const RichTextEditor = defineAsyncComponent(() => import("@/common/RichTextEditor/index.vue"));

// 拖拽相关状态
const drag = ref(false);

// 不同类型的拖拽配置选项
const dragOptions = computed(() => ({
  animation: 200,
  group: "item",
  disabled: false,
  ghostClass: "ghost",
  handle: ".drag-handle", // 只有拖拽手柄才能触发拖拽
  filter: ".rich-text-editor, .arco-input, .arco-select, .arco-checkbox", // 排除这些元素的拖拽
  preventOnFilter: false, // 允许在被过滤的元素上进行正常交互
}));

const buttonDragOptions = computed(() => ({
  animation: 200,
  group: "buttons", // 按钮专用分组
  disabled: false,
  ghostClass: "ghost",
  handle: ".drag-handle", // 只有拖拽手柄才能触发拖拽
  filter: ".arco-input, .arco-select, .arco-checkbox", // 排除输入框等元素
  preventOnFilter: false,
}));

const linkDragOptions = computed(() => ({
  animation: 200,
  group: "links", // 链接专用分组
  disabled: false,
  ghostClass: "ghost",
  handle: ".drag-handle", // 只有拖拽手柄才能触发拖拽
  filter: ".arco-input, .arco-select, .arco-checkbox", // 排除输入框等元素
  preventOnFilter: false,
}));

const categoryDragOptions = computed(() => ({
  animation: 200,
  group: "categories", // 分类专用分组
  disabled: false,
  ghostClass: "ghost",
  handle: ".drag-handle", // 只有拖拽手柄才能触发拖拽
  filter: ".arco-input, .arco-select, .arco-checkbox", // 排除输入框等元素
  preventOnFilter: false,
}));

const imageDragOptions = computed(() => ({
  animation: 200,
  group: "images", // 图片专用分组
  disabled: false,
  ghostClass: "ghost",
  handle: ".drag-handle", // 只有拖拽手柄才能触发拖拽
  filter: ".arco-input, .arco-select, .arco-checkbox", // 排除输入框等元素
  preventOnFilter: false,
}));

// 检查是否应该显示拖拽图标
const shouldShowDragHandle = (list: any[]) => {
  return list && list.length > 1;
};

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },

  data: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["update:show"]);

const handleCancel = () => {
  emit("update:show", false);
};

const handleAdd = (type: string) => {
  const detail = props.data;
  if (type === "Article") {
    detail.data.push({
      id: randomString(),
      type: "Article",
      title: "",
      content: "",
      buttonList: [],
      linkList: [],
    });
  } else if (type === "Contact") {
    detail.data.push({
      id: randomString(),
      type: "Contact",
      title: "",
      content: "",
      categories: [],
      linkList: [],
    });
  } else if (type === "Image") {
    detail.data.push({
      id: randomString(),
      type: "Image",
      imgSrc: "",
      caption: "",
      alt: "",
      isRound: false,
    });
  } else if (type === "ImageList") {
    detail.data.push({
      id: randomString(),
      type: "ImageList",
      imageList: [],
    });
  } else if (type === "Video") {
    detail.data.push({
      id: randomString(),
      type: "Video",
      videoSrc: "",
      imgSrc: "",
    });
  }
};

const handleDelete = (id: string) => {
  props.data.data = props.data.data.filter((item: any) => item.id !== id);
};

const handleAddButton = (list: any[]) => {
  list.push({
    id: randomString(),
    text: "查看更多",
    url: undefined,
    isExternal: false,
  });
};

const handleDeleteButton = (list: any[], id: string) => {
  list.splice(
    list.findIndex((item) => item.id === id),
    1
  );
};

const handleAddLink = (list: any[]) => {
  list.push({
    id: randomString(),
    text: "查看更多",
    url: undefined,
    isExternal: false,
  });
};

const handleDeleteLink = (list: any[], id: string) => {
  list.splice(
    list.findIndex((item) => item.id === id),
    1
  );
};

const handleAddCategory = (list: any[]) => {
  list.push({
    id: randomString(),
    text: "分类",
  });
};

const handleDeleteCategory = (list: any[], id: string) => {
  list.splice(
    list.findIndex((item) => item.id === id),
    1
  );
};
const handleAddImage = (list: any[]) => {
  list.push({
    id: randomString(),
    src: "",
  });
};

const handleDeleteImage = (list: any[], img: string) => {
  list.splice(
    list.findIndex((item) => item === img),
    1
  );
};
</script>

<style lang="scss" scoped>
.setting-content {
  .setting-header {
    padding-bottom: 12px;

    .header-title {
      width: 120px;
      padding-right: 12px;
      text-align: right;
    }
  }

  .setting-body {
    margin-top: 12px;

    .setting-item {
      position: relative;
      padding: 16px 12px;
      background: #f0f2f5;
      border-radius: 8px;
      margin-bottom: 20px;

      .btn-group {
        position: absolute;
        right: 0;
        top: 0;
        display: flex;
        align-items: center;
        padding: 4px;

        .btn-delete {
          padding: 4px;
          font-size: 24px;
          cursor: pointer;
        }
      }

      .item-name {
        font-size: 16px;
        font-weight: 600;
        padding-bottom: 10px;
        border-bottom: 1px solid #fff;
      }

      .item-title {
        padding: 12px 0 8px 0;
        font-size: 14px;
        font-weight: 600;
      }

      .arco-input-wrapper {
        background: #fff;
      }

      .item-button {
        position: relative;
        padding: 12px 8px 4px;
        background: #fff;
        border-radius: 4px;
        margin: 4px 0;
        transition: all 0.3s ease;

        &.draggable-item {          &:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
          }

          // 当禁用拖拽时，不显示拖拽效果
          &.sortable-disabled {
            cursor: default;

            &:hover {
              box-shadow: none;
              transform: none;
            }
          }
        }

        .arco-input-wrapper {
          background: #f2f3f5;
        }
      }

      // 拖拽相关样式
      .flip-list-move {
        transition: transform 0.5s;
      }

      .no-move {
        transition: transform 0s;
      }

      .ghost {
        opacity: 0.5;
        background: #c8ebfb;
      }

      .list-group {
        min-height: 20px;
      }

      .list-group-item {      }

      .list-group-item i {
        cursor: pointer;
      }

      .item-action {
        padding: 10px 0;

        .action-text {
          width: 150px;
          margin-right: 8px;
        }
      }

      .item-add-btn {
        display: inline-block;
        padding: 2px 8px;
        margin-top: 5px;
        font-size: 11px;
        color: #165dff;
        border-radius: 4px;
        font-weight: 600;
        border: 1px solid #165dff;
        cursor: pointer;
      }

      .item-img {
        margin-top: 12px;
        height: 160px;
      }

      .fit-content {
        width: fit-content;
      }

      .item-img-list {
        .img-list-item {
          margin: 4px 0;
          position: relative;
          padding: 8px;
          border-radius: 4px;
          transition: all 0.3s ease;
          background: #fff;
          border-radius: 4px;

          &.draggable-item {            &:hover {
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
              transform: translateY(-1px);
            }

            // 当禁用拖拽时，不显示拖拽效果
            &.sortable-disabled {
              cursor: default;

              &:hover {
                box-shadow: none;
                transform: none;
              }
            }
          }

          .arco-input-wrapper {
            background: #f2f3f5;
          }

          .img-drag-handle {
            top: 0 !important;
          }
        }

        .item-img-box {
          margin-right: 12px;
          position: relative;
          width: 133px;
          height: 100px;

          .item-img-dlete {
            position: absolute;
            padding: 8px;
            font-size: 32px;
            top: -16px;
            right: -16px;
            color: red;
            cursor: pointer;
          }
        }

        .small-img {
          margin: 0;
          height: 100px;
          object-fit: cover;
        }

        .item-right {
          padding-top: 24px;
        }
      }
    }
  }

  .drag-handle {
    padding: 4px;
    cursor: grab;
    padding: 4px;
    border-radius: 4px;

    &:hover {
      background-color: #f0f2f5;
    }

    &:active {
      cursor: grabbing;
    }

    .drag-icon {
      font-size: 16px;
      color: #86909c;
    }
  }
}
</style>
